package controllers.monorent;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import play.*;
import play.mvc.*;

import java.util.*;

import models.*;
import models.monorent.*;

import play.server.hybi10.Base64;

public class UsersRest extends Controller {

    static public void getAllUsers() {
		List<User> allUsers = User.findAll();
		renderJSON(allUsers, new UserSerializer());
	}

	static public void getUser(Long id) {
		User user = User.findById(id);
		if(user != null) {
			renderJSON(user, new UserSerializer());
		} else {
			renderJSON("invalid id");
		}
	}
	
	static public void createUser() {
		
		String email = params.get("email");
		String password = params.get("password");
		if(email == null || password == null) {
			renderJSON("email or password is null");
		} else if(email.equals("") || password.equals("")) {
			renderJSON("email or password is invalid");
		} else if(User.emailExists(email)) {
			renderJSON("email exists");
		} else {
			User u = new User(email, password).save();
			renderJSON(u, new UserSerializer());
		}
	}
	
	static public void updateUser(Long id) throws UnsupportedEncodingException {
		Http.Header authHeader = request.headers.get("authorization");
		if(authHeader == null) {
			renderJSON("auth needed");
			return;
		}
		String authString = authHeader.value();
		authString = authString.split(" ")[1];
		authString = new String(Base64.decode(authString), "UTF8");
		String[] authInfo = authString.split(":");
		if(authInfo.length < 2) {
			renderJSON("auth needed");
			return;
		}
		String authUsername = authInfo[0];
		String authPassword = authInfo[1];
		
		User user = User.findById(id);
		if(!authUsername.equals(user.email) || !authPassword.equals(user.password)) {
			renderJSON("auth failed");
			return;
		}
		
		if(user == null) {
			renderJSON("invalid id");
		} else {
			String action = params.get("action");
			if("delete".equals(action)) {
				deleteUser(id);
			} else {
				// update parameters
				if(params.get("password") != null) {
					user.password = params.get("password");
				}
				user.save();
				renderJSON(user, new UserSerializer());
			}
		}
	}
	
	static public void deleteUser(Long id) {
		User u = User.findById(id);
		u.delete();
		renderJSON("success");
	}
    
	
    
    
}
